/*
 * For com.royal.art
 * Copyright [2015/11/15] By FCHEN
 */
package com.manage.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * PageParamInterceptor
 * 分页参数拦截
 *
 * @author FCHEN
 * @date 2015/11/15
 */
public class PageParamInterceptor extends AbstractHandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (isPageRequest(request)) {
            setPageParams(request);
        }
        return true;
    }


    private boolean isPageRequest(HttpServletRequest request) {
        String path = request.getServletPath();
        path = StringUtils.substringBeforeLast(path, ".");
        return path.endsWith("list");
    }

    private void setPageParams(HttpServletRequest request) {
        Map<String, String[]> params = request.getParameterMap();
        if (null == params || params.isEmpty())
            return;
        List<JSONObject> pageParams = new ArrayList<JSONObject>();
        boolean skip;
        for (String key : params.keySet()) {
            skip = false;
            for (String pageParamsName : ingoreParams) {
                skip = key.equals(pageParamsName) || key.startsWith(pageParamsName);//跳过分页自带的参数
                if (skip) {
                    break;
                }
            }
            if (skip) {
                continue;
            }

            String[] values = params.get(key);
            if (null == values || values.length < 1) {
                continue;
            } else {
                JSONObject json = new JSONObject();
                json.put("name", key);
                json.put("value", Joiner.on(",").join(values));
                pageParams.add(json);
            }
        }
        if (!pageParams.isEmpty()) {
            String aoData = JSONObject.toJSONString(pageParams);
            request.setAttribute("aoData", aoData.substring(1, aoData.length() - 1));
        }
    }

    private final static List<String> ingoreParams = new ArrayList<String>();

    static {
        ingoreParams.add("sEcho");
        ingoreParams.add("iColumns");
        ingoreParams.add("sColumns");
        ingoreParams.add("iDisplayStart");
        ingoreParams.add("iDisplayLength");
        ingoreParams.add("mDataProp");
    }


}
